

import React, { useState, useEffect, useCallback } from "react";
import Taro from "@tarojs/taro";
import { Textarea, View, Input, Image, Text,ScrollView } from "@tarojs/components";
import TaroStatusBar from "@src/components/status-bar";
import { isAndriod } from "@src/utils";
import { createIssue, createSquare } from "@src/service";
import { uploadFiles } from "@src/utils/request/upload";
import { useAppDispatch, useAppSelector } from "@src/store";
import { getPostList } from "@src/store/postList";
import MediaNavBar from "@src/components/media-nav-bar";

import "./index.scss";
import { BackHandler } from "react-native";
import PageScreen from "@src/components/layout/PageScreen";
import {  deleteMediaChoosed } from "@src/store/globalData";


const PublishPage = React.forwardRef(() => {
    const [title, setTitle] = useState("");
    const [content, setContent] = useState("");
    const mediasChoosed = useAppSelector(state => state.globalData.imageChoosed);
    const [toolbarShow, setToolbarShow] = useState(false);

    const dispath = useAppDispatch();
    const backAction = useCallback(() => {
        const createDraft = async () => {
            const fileObjs: AnyObjType[] = [];

            // 构建File对象
            for (let i = 0; i < mediasChoosed.length; i++) {
                const filePath = mediasChoosed[i];
                if (!filePath) continue;
                const uri = isAndriod() ? filePath : filePath.replace("file://", "");
                const pathArr = uri.split("/");
                const fileObj = { uri: uri, type: "application/octet-stream", name: pathArr[pathArr.length - 1] };
                fileObjs.push(fileObj);
            }

            const medias: any[] = [];
            if (fileObjs.length !== 0) {
                try {
                    const res = await uploadFiles("medias/file/", fileObjs);
                    if (Object.is(res.data.code, 0)) {
                        const data = res.data.data;
                        const mediaId = data.id;
                        medias.push(mediaId);

                    } else {
                        Taro.showToast({
                            title: "上传文件失败"
                        });
                    }
                } catch (error) {
                    Taro.showToast({
                        title: "上传文件失败"
                    });
                }
            }

            const result = await createSquare({
                content,
                title,
                medias
            });
            console.log(result);
            Taro.showToast({
                title: "发布成功",
                icon: "success"
            });

        };

        Taro.showActionSheet({
            itemList: ["保存草稿", "不保存"],
            success: function (res) {
                if (res.tapIndex === 0) {
                    createDraft();
                }
                handleBack();
            },
            fail: function (res) {
                console.log(res.errMsg);
            }
        });
        return true;
    }, [content, title, mediasChoosed]);

    useEffect(() => {
        const backHandler = BackHandler.addEventListener("hardwareBackPress", backAction);
        return () => backHandler.remove();
    }, [content, title, backAction]);




    const publish = async () => {
        const fileObjs: AnyObjType[] = [];

        let medias: Array<string> = [];
        if (mediasChoosed.length > 0) {
            // 构建File对象
            for (let i = 0; i < mediasChoosed.length; i++) {
                const filePath = mediasChoosed[i].uri;
                if (!filePath) continue;
                const uri = isAndriod() ? filePath : filePath.replace("file://", "");
                const pathArr = uri.split("/");
                const fileObj = { uri: uri, type: "application/octet-stream", name: pathArr[pathArr.length - 1] };
                fileObjs.push(fileObj);
            }
            try {
                const res = await uploadFiles("medias/file/", fileObjs);
                if (Object.is(res.data.code, 0)) {
                    const data = res.data.data;
                    const mediaId = data.id;
                    medias.push(mediaId);

                } else {
                    Taro.showToast({
                        title: "上传文件失败"
                    });
                    return;
                }
            } catch (error) {
                Taro.showToast({
                    title: "上传文件失败"
                });
                return;
            }

        }

        const result = await createIssue({
            content,
            title,
            status: "published",
            medias
        });
        if (Object.is(result.data.code, 0)) {
            Taro.showToast({
                title: "发布成功",
                icon: "success"
            });
            dispath(getPostList({}));
            handleBack();
        } else {
            Taro.showToast({
                title: "发布失败",
                icon: "success"
            });
        }

    };

    const handleBack = ()=>{
        // TODO 清除已经选中的媒体资源
        const pageStack = Taro.getCurrentPages();
        Taro.navigateBack({
            delta:pageStack.length - 1
        });
        // Taro.reLaunch({
        //     url:"/pages/tab_home/index"
        // });
    };


    const handleTextAreaInput = (event) => {
        setContent(event.target.value
        );
    };

    const handleTitleInput = (event) => {
        setTitle(event.target.value);
    };


    const handleTextAreaFocus = () => {
        setToolbarShow(true);
    };
    const handleTextAreaBlur = () => {
        setToolbarShow(false);
    };

    const handleAddMoreMedia = ()=>{
        Taro.navigateTo({
            url:"/pages/mediaGallery/index"
        });
    };

    const handleDeleteOneMedia = useCallback((index)=>{
        dispath(deleteMediaChoosed(index));
    },[dispath]);


    return (
        <PageScreen edges={["right", "bottom", "left", "top"]} style={{ height: "100%" }}>
           
            <View className="publish__page">
                <MediaNavBar next={publish} nextText="发布" textColor="#000" canNext back={backAction} />
                <View className="publish__media__preview__swiperWrapper">
                <ScrollView className="publish__media__preview" scrollX>
                    {
                        mediasChoosed.map((media, index) => <View className="publish__media__preview__item" key={media.uri}>
                            <Image className="publish__media__preview__item__image" src={media.uri} mode="aspectFill" />
                            <View className=" publish__media__preview__item__deleteBtn"  onClick={handleDeleteOneMedia.bind(null,index)}>
                                <Text className="ionicons deleteIcon">{"\uf228"}</Text> </View>
                        </View>
                        )
                    }
                    <View className="publish__media__preview__item" onClick={handleAddMoreMedia}>
                    <View className="publish__media__preview__item__addMore">
                        <Text className="ionicons addMoreIcon">{"\uf100"}</Text>
                    </View>
                    </View>
                   
                </ScrollView>
                </View>
               
                <View className="publish__title">
                    <Input value={title} className="publish__title__input" onInput={handleTitleInput} placeholder="添加标题" />
                    <Text className="publish__title__input__tip">0/20</Text>
                </View>
                <Textarea className="publish__textArea" disableDefaultPadding holdKeyboard value={content} placeholder="添加你的作品描述吧" onInput={handleTextAreaInput} onFocus={handleTextAreaFocus} onBlur={handleTextAreaBlur} />

                <View className="publish__operateBar">

                    {
                        toolbarShow ? <View className="publish__toolBar">
                            <View> # 添加话题</View>

                        </View> : null
                    }


                </View>
            </View>
        </PageScreen>
    );
});


export default PublishPage;
